package com.learn.concurrent.itcast.thread.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OddEvenDemo {

    private int i=0;//要打印的数
    //private Object obj=new Object();
    private Lock lock = new ReentrantLock();//参数是是否公平锁：true-公平锁，多个线程都公平拥有执行权；false-非公平，独占锁，默认值
    private Condition condition=lock.newCondition();

    /**
     * 奇数打印方法，由奇数线程调用
     */
    public void odd() {
        while(i<10){
            lock.lock();
            try {
                if(i%2==1){
                    System.out.println(Thread.currentThread().getName()+" 奇数："+i);
                    i++;
                    condition.signal();//唤醒偶数线程打印
                }else{
                    try {
                        condition.await();//等待偶数线程打印完毕
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }

    /**
     * 偶数打印方法，由偶数线程调用
     */
    public void even(){
        while(i<10){
            lock.lock();
            try {
                if(i%2==0){
                    System.out.println(Thread.currentThread().getName()+" 偶数："+i);
                    i++;
                    condition.signal();//唤醒奇数线程打印
                }else{
                    try {
                        condition.await();//等待奇数线程打印完毕
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }
    public static void main(String[] args) {
        final OddEvenDemo demo=new OddEvenDemo();
        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                demo.odd();
            }
        },"奇数线程");

        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                demo.even();
            }
        },"偶数线程");

        thread1.start();
        thread2.start();
    }
}
